package com.bjb.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class LoginUtil {
	
	public static final String USER_KEY = "LoginUserKey";// 登录用户key
	
	public static final String USER_ROLE_KEY = null; // 登录用户角色key
	
	public static final String COOKIE = "userId";
	
	public static final Integer COOKIE_TIME =1800;//sso ticket time
	
	public static void setCookie(HttpServletResponse response,String userId){
		Cookie cookie=new Cookie(LoginUtil.COOKIE,userId);
		cookie.setMaxAge(COOKIE_TIME);				//设置生命周期为30分钟
		cookie.setPath("/");				//设置路径为根路径
		response.addCookie(cookie);
	}
	
	public static void coverCookie(String userId,Integer time){
		Cookie cookie=new Cookie(LoginUtil.COOKIE,userId);
		cookie.setMaxAge(time);				//设置生命周期为30分钟
		cookie.setPath("/");				//设置路径为根路径
		getResponse().addCookie(cookie);
	}
	
	public static Integer getCookie(HttpServletRequest request){
		Cookie[] cookies = request.getCookies();
		Integer userId = 0;
		if(cookies!=null){
			for(Cookie cookie:cookies){
				if(cookie.getName().equals("userId")){
					if(cookie.getValue()!=null&&!cookie.getValue().equals("")){
						userId = Integer.parseInt(cookie.getValue());
					}
				}
			}
		}
		return userId;
	}
	
	public static void destroyCookie(HttpServletRequest request,HttpServletResponse response){
		Cookie [] cookies=request.getCookies();
		if(cookies != null){
			for(Cookie cookie:cookies){
				if(cookie.getName().equals(LoginUtil.COOKIE)){
					
					String cookieTicket=cookie.getValue();
					
					LoginUtil.coverCookie( cookieTicket,0);

					break;
				}
			}
		}
	}
	
	public static HttpSession getSession(boolean flag){
		
		HttpSession session = null;
		session = getRequest().getSession(flag);
		return session;
	}
	
    public static HttpSession getSession() { 
		HttpSession session = null; 
		session=getRequest().getSession();
		session.setMaxInactiveInterval(30*60);//过期时间
		return session;
	} 
	
	public static HttpServletRequest getRequest() { 
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 
		return attrs.getRequest(); 
	}
	
	public static HttpServletResponse getResponse() { 
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 
		return attrs.getResponse(); 
	}
}
